package com.xique.auth.service;

import cn.hutool.core.util.ObjectUtil;
import com.xique.common.core.constant.CacheConstants;
import com.xique.common.core.constant.Constants;
import com.xique.common.core.constant.UserConstants;
import com.xique.common.core.domain.R;
import com.xique.common.core.enums.UserStatus;
import com.xique.common.core.exception.BaseException;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.ServletUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.utils.sign.RsaUtils;
import com.xique.park.api.request.RemoteParkClientLogService;
import com.xique.system.api.RemoteSystemLogService;
import com.xique.system.api.RemoteSystemUserService;
import com.xique.system.api.dto.SystemUserDTO;
import com.xique.system.api.model.LoginSystemUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 登录校验方法
 *
 * @author xique
 */
@Component
public class SysLoginService
{

    @Autowired
    private RemoteSystemLogService remoteSystemLogService;

    @Autowired
    private RemoteSystemUserService remoteSystemUserService;

    @Autowired
    private RemoteParkClientLogService remoteParkClientLogService;

    @Value("${xique.api.privateKey}")
    private String privateKey;

    /**
     * 登录
     */
    public LoginSystemUser login(String username, String password)
    {
        String platform = ServletUtils.getHeaders(Objects.requireNonNull(ServletUtils.getRequest())).get(CacheConstants.DETAILS_PLATFORM_TYPE);
        try {
            password = RsaUtils.decryptByPrivateKey(privateKey, password);
        } catch (Exception e) {
            throw new BaseException("密码解析错误");
        }
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "用户/密码必须填写", platform);
            throw new BaseException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "用户密码不在指定范围", platform);
            throw new BaseException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "用户名不在指定范围", platform);
            throw new BaseException("用户名不在指定范围");
        }
        // 查询用户信息
        R<LoginSystemUser> userResult = remoteSystemUserService.getUserInfo(username);
        if (R.FAIL == userResult.getCode())
        {
            throw new BaseException(userResult.getMsg());
        }
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "登录用户不存在", platform);
            throw new BaseException("登录用户：" + username + " 不存在");
        }
        LoginSystemUser userInfo = userResult.getData();
        SystemUserDTO user = userResult.getData().getSystemUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除", platform);

            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员", platform);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        if (UserConstants.Platform.CLIENT.equals(platform) && !UserConstants.Type.CLIENT.equals(user.getType())) {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "非岗亭账号不能登录", platform);
            throw new BaseException("非岗亭账号不能登录");
        }
        if (UserConstants.Platform.APP_PARK.equals(platform) && UserConstants.Type.CLIENT.equals(user.getType())) {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "岗亭账号不能登录", platform);
            throw new BaseException("岗亭账号不能登录");
        }
        if (UserConstants.Platform.APP_PARK.equals(platform) && ObjectUtil.isEmpty(user.getParkId())) {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "非车场账号不能登录", platform);
            throw new BaseException("非车场账号不能登录");
        }
        if (UserConstants.Platform.CLIENT.equals(platform) && SecurityUtils.matchesPasswordWithOldVersion(password, userResult.getData().getSystemUser().getLoginName(), userResult.getData().getSystemUser().getSalt(), userResult.getData().getSystemUser().getPassword())) {
            userResult = remoteSystemUserService.getUserInfoWithUpdatePassword(username, password);
            if (R.FAIL == userResult.getCode())
            {
                throw new BaseException(userResult.getMsg());
            }
            userInfo = userResult.getData();
            user = userResult.getData().getSystemUser();
        }
        if (!SecurityUtils.matchesPasswordWithOldVersion(password, user.getLoginName(), user.getSalt(), user.getPassword()) && !SecurityUtils.matchesPassword(password, user.getPassword()))
        {
            remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_FAIL, "用户密码错误", platform);
            throw new BaseException("用户不存在/密码错误");
        }
        remoteSystemLogService.saveLoginInfo(username, Constants.LOGIN_SUCCESS, "登录成功", platform);
        return userInfo;
    }

    public void logout(String loginName)
    {
        String platform = ServletUtils.getHeaders(Objects.requireNonNull(ServletUtils.getRequest())).get(CacheConstants.DETAILS_PLATFORM_TYPE);
        remoteSystemLogService.saveLoginInfo(loginName, Constants.LOGOUT, "退出成功", platform);
    }

    public void clientLogout(String loginName, Long clientId)
    {
        String platform = ServletUtils.getHeaders(Objects.requireNonNull(ServletUtils.getRequest())).get(CacheConstants.DETAILS_PLATFORM_TYPE);
        remoteSystemLogService.saveLoginInfo(loginName, Constants.LOGOUT, "退出成功", platform);
        remoteParkClientLogService.deleteClientUserInfo(clientId);
        remoteParkClientLogService.saveClientLogininfor(clientId, loginName, Constants.LOGOUT, "退出成功");
    }
}
